﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace yq
{
    /// <summary>
    /// 重新加载数据
    /// </summary>
    public class CaCheRefresh
    {
        public IList<FullAndId> list = new List<FullAndId>();


        /// <summary>
        /// 添加对象
        /// </summary>
        /// <param name="id"></param>
        public void Add<T>(string id,object obj) where T : new()
        {
            list.Add(new FullAndId() 
            { 
                Fullname = new T().GetType().FullName,
                Id = id, Object = obj, 
                Type= CaCheRefreshType.Add 
            });
        }

        public void Delete<T>(string id) where T : new()
        {
            list.Add(new FullAndId() 
            { 
              Fullname = new T().GetType().FullName,
              Id = id, 
              Type= CaCheRefreshType.Delete 
            });
        }

        public void Update<T>(string id, object obj) where T : new()
        {
            list.Add(new FullAndId() 
            {
                Fullname = new T().GetType().FullName,
                Id = id,
                Object = obj ,
                Type= CaCheRefreshType.Update
            });
        }

        /// <summary>
        /// 正常执行更新缓存方法
        /// </summary>
        /// <param name="type"></param>
        /// <param name="id"></param>
        public void Do()
        {
            foreach (var info in list)
            {
                if (info.Type == CaCheRefreshType.Delete)
                {
                    yq.CaChe<object>.RefreshDelete(info.Fullname, info.Id);
                }
                else
                {
                    yq.CaChe<object>.RefreshLoad(info.Fullname, info.Id, info.Object);
                }
            }
        }

        /// <summary>
        /// 异常时直接清理缓存，以免出现数据差异
        /// </summary>
        public void DoTry()
        {
            foreach (var r in list)
            {
                yq.CaChe<object>.RefreshDelete(r.Fullname, r.Id);
            }
        }

    }

    /// <summary>
    /// 修改方式
    /// </summary>
    public enum CaCheRefreshType
    {
        Delete,
        Add,
        Update
    }

    public class FullAndId
    {
        public string Fullname
        {
            get;
            set;
        }

        public string Id
        {
            get;
            set;
        }

        public object Object
        {
            get;
            set;
        }

        public CaCheRefreshType Type
        {
            get;
            set;
        }
        
    }
}
